package com.example.springboot.controller;

import cn.hutool.core.lang.Dict;
import com.example.springboot.common.Result;
import com.example.springboot.service.ProductService;
import com.example.springboot.service.impl.ProductScoreServiceImpl;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

/**
 * 商品表(Product)表控制层
 *
 * @author makejava
 * @since 2024-01-13 17:16:26
 */
@RestController
@RequestMapping("/product")
public class ProductController {
    /**
     * 服务对象
     */
    @Autowired
    private ProductService productService;
    @Autowired
    private ProductScoreServiceImpl productScoreService;


    /**
     * 测试接口
     *
     * @return
     */
    @PostMapping("/test")
    public Result test() {
        return Result.success(productService.test());
    }


    /**
     * 获取所有商品信息
     *
     * @return
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        return Result.success(productService.selectAll());
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Integer id) {
        productService.deleteById(id);
        return Result.success("删除成功!");
    }

    /**
     * 更新商品信息
     *
     * @param product
     * @return
     */
    @PutMapping("/updateById")
    public Result updateById(@RequestBody Product product) {
        productService.updateById(product);
        return Result.success("更新成功！");
    }


    /**
     * 条件查询
     *
     * @param username
     * @param name
     * @param phone
     * @param status
     * @return
     */
    @GetMapping("/selectByManyCondition")
    public Result selectByManyCondition(@RequestParam("username") String username,
                                        @RequestParam("name") String name,
                                        @RequestParam("phone") String phone,
                                        @RequestParam("status") Integer status) {
        return Result.success(productService.selectByManyCondition(username, name, phone, status));
    }

    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param storeName
     * @param categoryName
     * @param status
     * @return
     */
    @GetMapping("/selectByManyConditionInpage")
    public Result selectByManyConditionInpage(@RequestParam("currentPage") Integer currentPage,
                                              @RequestParam("pageSize") Integer pageSize,
                                              @RequestParam("name") String name,
                                              @RequestParam("storeName") String storeName,
                                              @RequestParam("categoryName") String categoryName,
                                              @RequestParam("status") Integer status) {
        return Result.success(productService.selectByManyConditionInpage(currentPage, pageSize, name, storeName, categoryName, status));
    }


    /**
     * 条件查询  分页
     *
     * @param currentPage
     * @param pageSize
     * @param name
     * @param storeName
     * @param categoryName
     * @return
     */
    @GetMapping("/selectByManyConditionNoStatusInpage")
    public Result selectByManyConditionNoStatusInpage(@RequestParam("currentPage") Integer currentPage,
                                                      @RequestParam("pageSize") Integer pageSize,
                                                      @RequestParam("name") String name,
                                                      @RequestParam("storeName") String storeName,
                                                      @RequestParam("categoryName") String categoryName) {
        return Result.success(productService.selectByManyConditionNoStatusInpage(currentPage, pageSize, name, storeName, categoryName));
    }

    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam("currentPage") Integer currentPage,
                               @RequestParam("pageSize") Integer pageSize) {
        return Result.success(productService.selectByPage(currentPage, pageSize));
    }


    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/deleteByIds")
    public Result deleteByIds(@RequestBody List<Integer> ids) {
        productService.deleteByIds(ids);
        return Result.success("删除成功！");
    }


    /**
     * 添加店铺
     *
     * @param product
     * @return
     */
    @PostMapping("/addProduct")
    public Result addProduct(@RequestBody Product product) {
        productService.addProduct(product);
        return Result.success("添加成功！");
    }


    /**
     * 店铺详情
     *
     * @param id
     * @return
     */
    @GetMapping("/productInfo")
    public Result productInfo(@RequestParam("id") Integer id) {
        Product product = productService.selectById(id);
        // 对当前商品的浏览量自增
        product.setViews(product.getViews().add(BigDecimal.ONE));
        productService.update(product);
        // 获取当前商品的评分
        User currentUser = TokenUtils.getCurrentUser();
        if (currentUser != null) {
            // 更新评分表，如果没有则插入一条数据，如果有，则判断是否比1分小，如果小更改为1分，如果大不更改
            ProductScore productScore = new ProductScore();
            productScore.setProductId(Long.valueOf(String.valueOf(id)));
            productScore.setUserId(Long.valueOf(String.valueOf(currentUser.getId())));

            // 查询评分表是否有该商品的评分
            ProductScore productScore1 = productScoreService.select(productScore);
            productScore.setScore(1.0f);
            if (productScore1 != null) {
                // 判断是否比1分小
                if (productScore1.getScore() < 1.0f) {
                    productScoreService.update(productScore);
                }
            } else {
                productScoreService.insert(productScore);
            }
        }
        return Result.success(product);
    }


    /**
     * 获取商品数量
     *
     * @return
     */
    @PostMapping("/getTotal")
    public Result getTotal() {
        return Result.success(productService.getTotal());
    }


    @GetMapping("/loadStoreProducts")
    public Result loadStoreProducts(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("id") Integer id) {
        return Result.success(productService.loadStoreProducts(currentPage, pageSize, id));
    }


    @PostMapping("/getStoreTotal")
    public Result getStoreTotal(@RequestParam("id") Integer id) {
        return Result.success(productService.getStoreTotal(id));
    }

    @GetMapping("/selectByPageInStore")
    public Result selectByPageInStore(@RequestParam("currentPage") Integer currentPage,
                                      @RequestParam("pageSize") Integer pageSize,
                                      @RequestParam("id") Integer id) {
        return Result.success(productService.selectByPageInStore(currentPage, pageSize, id));
    }

    // 基于用户的协同过滤算法实现的推荐页面
    @GetMapping("/mainProducts")
    public Result mainProducts() {
        try {
            User currentUser = TokenUtils.getCurrentUser();
            Dict dict = productService.mainProducts();
            List<Product> recommendedProducts = (List<Product>) dict.get("recommendedProducts");
            // 通过协同过滤算法获取用户可能喜欢的东西
            List<Product> recommend = productScoreService.recommend(Long.valueOf(String.valueOf(currentUser.getId())), 3);
            // 合并两个列表，将原来的推荐替换为现在的三个推荐，如果推荐的数量小于三个，则随机补足
            if (recommend.size() < 3) {
                List<Product> randomProducts = productService.getRandomProducts(3 - recommend.size());
                recommend.addAll(randomProducts);
            }
            dict.set("recommendedProducts", recommend);
            return Result.success(dict);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取主页商品失败！");
        }
    }


    @PostMapping("/selectByCategory")
    public Result selectByCategory(@RequestParam("currentPage") Integer currentPage,
                                   @RequestParam("pageSize") Integer pageSize,
                                   @RequestParam("id") Integer id) {
        return Result.success(productService.selectByCategory(currentPage, pageSize, id));
    }

    @GetMapping("/getRandomProducts")
    public Result getRandomProducts(@RequestParam("size") Integer size) {
        return Result.success(productService.getRandomProducts(size));
    }

    @PostMapping("/selectByCondition")
    public Result selectByCondition(@RequestParam("currentPage") Integer currentPage,
                                    @RequestParam("pageSize") Integer pageSize,
                                    @RequestParam("condition") String condition) {
        return Result.success(productService.selectByCondition(currentPage, pageSize, condition));
    }

    @PostMapping("/loadStoreNewProducts")
    public Result loadStoreNewProducts(@RequestParam("id") Integer id) {
        return Result.success(productService.loadStoreNewProducts(id));
    }

    @PostMapping("/loadRecommendedProducts")
    public Result loadRecommendedProducts(@RequestParam("id") Integer id) {
        return Result.success(productService.loadRecommendedProducts(id));
    }

    @PostMapping("/update")
    public Result update(@RequestBody Product product) {
        productService.update(product);
        return Result.success("修改成功！");
    }

}

